import * as roleApi from '@/api/company'

const state = {
  companyList: [],
  companyDetails: {},
  permissions: [],
  permissionsDtails: [],
  rolePeimissionsList: []
}

const mutations = {
  SET_COMPANY_LIST(state, newValue) {
    state.companyList = newValue
  },
  SET_COMPANYDETAILE_LIST(state, newValue) {
    state.companyDetails = newValue
  },
  SET_PERMISSION_LIST(state, newValue) {
    state.permissions = newValue
  },
  SET_PERMISSION_DETAILES(state, newValue) {
    state.permissionsDtails = newValue
  },
  SET_ROLEPERMISSION_LIST(state, newValue) {
    state.rolePeimissionsList = newValue
  },
}

const actions = {
  async updateCompanyList({ commit }) {
    const res = await roleApi.getCompany()
    commit('SET_COMPANY_LIST', res)
  },
  async updatecompanyDetailList({ commit }, id) {
    const res = await roleApi.getCompanyDetails(id)
    commit('SET_COMPANYDETAILE_LIST', res)
  },
  // 权限列表
  async updatePermissionList({ commit }) {
    const res = await roleApi.getPermissions()
    commit('SET_PERMISSION_LIST', res)
  },
  // 角色权限
  async updateRolePermissionList({ commit }, id) {
    const res = await roleApi.getRolePermissions(id)
    commit('SET_ROLEPERMISSION_LIST', res)
  },
  // 权限详情
  async updatePermissionDetails({ commit }, id) {
    const res = await roleApi.getPermissionDetails(id)
    commit('SET_PERMISSION_DETAILES', res)
  },
}

function dataTansfer(data, pid) {
  return data
    .filter(d => d.pid === pid)
    .map(item => ({
      ...item,
      children: dataTansfer(data, item.id)
    }))
}
const getters = {
  companyTree(state) {
    return dataTansfer(state.companyList, '')
  },
  permissionsTree(state) {
    return dataTansfer(state.permissions, '0')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
